package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY_LIST;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY_STR;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        // 从缓存中查询
        // Solution 1 使用String格式
        String typeJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY_STR);
        if (StrUtil.isNotBlank(typeJson)) {
            List<ShopType> typeList1 = JSONUtil.toList(typeJson, ShopType.class);
            // return Result.ok(typeList1);
        }

        // Solution 2 使用List格式
        List<String> typeList2 = stringRedisTemplate.opsForList()
                .range(CACHE_SHOP_TYPE_KEY_LIST, 0, -1);
        if (CollectionUtil.isNotEmpty(typeList2)) {
            List<ShopType> collect = typeList2.stream()
                    .map(t -> JSONUtil.toBean(t, ShopType.class))
                    .collect(Collectors.toList());
            return Result.ok(collect);
        }


        // 缓存中不存在，查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();

        // 将查询结果存入缓存 (String)
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY_STR, JSONUtil.toJsonStr(typeList));
        // 将查询结果存入缓存 (List)
        stringRedisTemplate.opsForList()
                .rightPushAll(CACHE_SHOP_TYPE_KEY_LIST, typeList.stream()
                        .map(t -> JSONUtil.toJsonStr(t))
                        .collect(Collectors.toList()));


        return Result.ok(typeList);
    }
}
